package com.joey.concurrency.example.commUnsafe;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joey.concurrency.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Author hyy
 **/
@Slf4j
@ThreadSafe
public class CollectionsExample2 {
    public static int clientCount = 1000;
    public static int threadTotal = 200;
    public static Set<Integer> set = Collections.synchronizedSet(Sets.newHashSet());
    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientCount);
        for(int i=0;i<clientCount;i++){
            final int index = i;
            executorService.execute(() -> {
                try {
                    //判断当前进程是否被执行
                    semaphore.acquire();
                    update(index);
                    semaphore.release();
                }catch (Exception e){
                    log.error("exception",e);
                }
                countDownLatch.countDown();

            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("length {}",set.size());
    }

    public static void update(int index){
        set.add(index);

    }
}
